import React, { useRef, useEffect, useState } from 'react';
import style from './Canvas.module.css';
import Stylebeautification from '../Stylebeautification/Stylebeautification';
// import MyEditor from '../MyEditor'
// import Char from '../../pages/Char/Char'
import Char from '../../pages/char/char'
function Canvas() {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const images = useRef<{ src: string; x: number; y: number; width: number; height: number; scaleX: number; scaleY: number; isSelected: boolean }[]>([]).current;
  const [selectedImageIndex, setSelectedImageIndex] = useState<number | null>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [offset, setOffset] = useState<{ x: number; y: number } | null>(null);
  const [isResizing, setIsResizing] = useState(false);
  const [resizeCorner, setResizeCorner] = useState<'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight' | null>(null);
  const [canvasBackground, setCanvasBackground] = useState(null);
  const [backgroundUrl, setBackgroundUrl] = useState(null);
  const [xyx, SetXyx] = useState(null);
  const [xyy, SetXyy] = useState(null);
  const [img, setImg] = useState('');
  const [showWatermark, setShowWatermark] = useState(true);
  const [canvasWidth, setCanvasWidth] = useState(1000);
  const [canvasHeight, setCanvasHeight] = useState(600);
  const [sharePreview, setSharePreview] = useState(false);
  const handleShare = () => {
    const canvas = canvasRef.current;
    if (canvas) {
      // 显示预览窗口
      setSharePreview(true);
      // 可以将dataURL保存到状态中，然后在预览窗口中使用
    }
  };

  const handleClosePreview = () => {
    setSharePreview(false);
  };
  useEffect(() => {
    const canvas = canvasRef.current;
    if (canvas) {
      const context = canvas.getContext('2d');
      if (context) {
        canvas.style.width = canvasWidth + 'px';
        canvas.style.height = canvasHeight + 'px';
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;
        drawImages(context);
      }
    }
  }, [canvasWidth, canvasHeight]);

  const deleteSelectedImage = () => {
    if (selectedImageIndex !== null) {
      images.splice(selectedImageIndex, 1);
      setSelectedImageIndex(null);
      drawImages(canvasRef.current!.getContext('2d')!);
    }
  };

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const context = canvas.getContext('2d');
    if (!context) return;
    canvas.width = 1000;
    canvas.height = 600;
    drawImages(context);
  }, []);

  const drawImages = (context: CanvasRenderingContext2D) => {
    context.clearRect(0, 0, context.canvas.width, context.canvas.height);
    images.forEach(({ src, x, y, width, height, scaleX, scaleY, isSelected }) => {
      const img = new Image();
      img.src = src;
      if (img) {
        context.save();
        context.translate(x + width / 2, y + height / 2);
        context.scale(scaleX, scaleY);
        context.translate(-width / 2, -height / 2);
        context.drawImage(img, 0, 0, width, height);
        context.restore();
        if (isSelected) {
          context.beginPath();
          context.arc(x, y, 5, 0, 2 * Math.PI);
          context.fillStyle = 'blue';
          context.fill();
          context.beginPath();
          context.arc(x + width, y, 5, 0, 2 * Math.PI);
          context.fillStyle = 'blue';
          context.fill();
          context.beginPath();
          context.arc(x, y + height, 5, 0, 2 * Math.PI);
          context.fillStyle = 'blue';
          context.fill();
          context.beginPath();
          context.arc(x + width, y + height, 5, 0, 2 * Math.PI);
          context.fillStyle = 'blue';
          context.fill();
        }
      }
    });
    if (showWatermark) {
      drawWatermark(context);

    }
  };

  const drawWatermark = (context: CanvasRenderingContext2D) => {
    context.save();
    context.globalAlpha = 0.2;
    context.font = '40px Arial';
    context.fillStyle = 'black';
    const text = '水印文字';
    const textWidth = context.measureText(text).width;
    const textHeight = 100;
    const xSpacing = textWidth * 2;
    const ySpacing = textHeight * 2;
    for (let y = 0; y < context.canvas.height; y += ySpacing) {
      for (let x = 0; x < context.canvas.width; x += xSpacing) {
        context.fillText(text, x, y);
      }
    }
    context.restore();
  };

  const handleToggleWatermark = () => {
    setShowWatermark((prev) => !prev);
    const canvas = canvasRef.current;
    if (canvas) {
      const context = canvas.getContext('2d');
      if (context) {
        drawImages(context);
      }
    }
  };

  useEffect(() => {
    const canvas = canvasRef.current;
    if (canvas) {
      const context = canvas.getContext('2d');
      if (context) {
        drawImages(context);
      }
    }
  }, [showWatermark]);

  const handleDrop = (event: DragEvent) => {
    event.preventDefault();
    const src = event.dataTransfer.getData('text/plain');
    const canvas = canvasRef.current;
    if (canvas) {
      const rect = canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const img = new Image();
      img.src = src;
      img.onload = () => {
        images.push({ src, x, y, width: img.width, height: img.height, scaleX: 1, scaleY: 1, isSelected: false });
        const context = canvas.getContext('2d');
        if (context) {
          drawImages(context);
        }
      };
    }
  };

  const handleDragOver = (event: DragEvent) => {
    event.preventDefault();
  };

  const handleCanvasClick = (event: React.MouseEvent<HTMLDivElement>) => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    let newSelectedIndex = null;
    images.forEach((image, index) => {
      if (x >= image.x && x <= image.x + image.width && y >= image.y && y <= image.y + image.height) {
        newSelectedIndex = index;
      }
    });
    if (selectedImageIndex !== null) {
      images[selectedImageIndex].isSelected = false;
    }
    if (newSelectedIndex !== null) {
      images[newSelectedIndex].isSelected = true;
      console.log(`选中的图片路径：${images[newSelectedIndex].src}`);
      localStorage.setItem('imagess', images[newSelectedIndex].src);
      setImg(images[newSelectedIndex].src);
    }
    setSelectedImageIndex(newSelectedIndex);
    const context = canvas.getContext('2d');
    if (context) {
      if (showWatermark) {
        drawImages(context);
      } else {
        context.clearRect(0, 0, context.canvas.width, context.canvas.height);
        images.forEach(({ src, x, y, width, height, scaleX, scaleY, isSelected }) => {
          const img = new Image();
          img.src = src;
          if (img) {
            context.save();
            context.translate(x + width / 2, y + height / 2);
            context.scale(scaleX, scaleY);
            context.translate(-width / 2, -height / 2);
            context.drawImage(img, 0, 0, width, height);
            context.restore();
            if (isSelected) {
              context.beginPath();
              context.arc(x, y, 5, 0, 2 * Math.PI);
              context.fillStyle = 'red';
              context.fill();
              context.beginPath();
              context.arc(x + width, y, 5, 0, 2 * Math.PI);
              context.fillStyle = 'red';
              context.fill();
              context.beginPath();
              context.arc(x, y + height, 5, 0, 2 * Math.PI);
              context.fillStyle = 'red';
              context.fill();
              context.beginPath();
              context.arc(x + width, y + height, 5, 0, 2 * Math.PI);
              context.fillStyle = 'red';
              context.fill();
            }
          }
        });
      }
    }
  };

  const handleMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
    const canvas = canvasRef.current;
    if (!canvas || selectedImageIndex === null) return;
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    const img = images[selectedImageIndex];
    if (x >= img.x && x <= img.x + img.width && y >= img.y && y <= img.y + img.height) {
      setIsDragging(true);
      setOffset({ x: x - img.x, y: y - img.y });
    } else {
      const cornerRadius = 5;
      if (Math.sqrt((x - img.x) ** 2 + (y - img.y) ** 2) <= cornerRadius) {
        setIsResizing(true);
        setResizeCorner('topLeft');
      } else if (Math.sqrt((x - (img.x + img.width)) ** 2 + (y - img.y) ** 2) <= cornerRadius) {
        setIsResizing(true);
        setResizeCorner('topRight');
      } else if (Math.sqrt((x - img.x) ** 2 + (y - (img.y + img.height)) ** 2) <= cornerRadius) {
        setIsResizing(true);
        setResizeCorner('bottomLeft');
      } else if (Math.sqrt((x - (img.x + img.width)) ** 2 + (y - (img.y + img.height)) ** 2) <= cornerRadius) {
        setIsResizing(true);
        setResizeCorner('bottomRight');
      }
    }
  };

  const handleMouseMove = (event: React.MouseEvent<HTMLDivElement>) => {
    if (isDragging && selectedImageIndex !== null) {
      const canvas = canvasRef.current;
      if (!canvas) return;
      const rect = canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const img = images[selectedImageIndex];
      img.x = x - offset.x;
      img.y = y - offset.y;
      SetXyx(img.x.toFixed(0));
      SetXyy(img.y.toFixed(0));
      const context = canvas.getContext('2d');
      if (context) {
        drawImages(context);
      }
    } else if (isResizing && selectedImageIndex !== null) {
      const canvas = canvasRef.current;
      if (!canvas) return;
      const rect = canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const img = images[selectedImageIndex];
      switch (resizeCorner) {
        case 'topLeft':
          img.x = x;
          img.y = y;
          img.width = images[selectedImageIndex].x + images[selectedImageIndex].width - x;
          img.height = images[selectedImageIndex].y + images[selectedImageIndex].height - y;
          img.scaleX = img.width / (images[selectedImageIndex].width * images[selectedImageIndex].scaleX);
          img.scaleY = img.height / (images[selectedImageIndex].height * images[selectedImageIndex].scaleY);
          break;
        case 'topRight':
          img.y = y;
          img.width = x - images[selectedImageIndex].x;
          img.height = images[selectedImageIndex].y + images[selectedImageIndex].height - y;
          img.scaleX = img.width / (images[selectedImageIndex].width * images[selectedImageIndex].scaleX);
          img.scaleY = img.height / (images[selectedImageIndex].height * images[selectedImageIndex].scaleY);
          break;
        case 'bottomLeft':
          img.x = x;
          img.width = images[selectedImageIndex].x + images[selectedImageIndex].width - x;
          img.height = y - images[selectedImageIndex].y;
          img.scaleX = img.width / (images[selectedImageIndex].width * images[selectedImageIndex].scaleX);
          img.scaleY = img.height / (images[selectedImageIndex].height * images[selectedImageIndex].scaleY);
          break;
        case 'bottomRight':
          img.width = x - images[selectedImageIndex].x;
          img.height = y - images[selectedImageIndex].y;
          img.scaleX = img.width / (images[selectedImageIndex].width * images[selectedImageIndex].scaleX);
          img.scaleY = img.height / (images[selectedImageIndex].height * images[selectedImageIndex].scaleY);
          break;
        default:
          break;
      }
      const context = canvas.getContext('2d');
      if (context) {
        drawImages(context);
      }
    }
  };

  const handleMouseUp = (event: React.MouseEvent<HTMLDivElement>) => {
    if (isDragging && selectedImageIndex !== null) {
      const canvas = canvasRef.current;
      if (!canvas) return;
      const rect = canvas.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      const img = images[selectedImageIndex];
      img.x = x - offset.x;
      img.y = y - offset.y;
      setIsDragging(false);
      setOffset(null);
      setSelectedImageIndex(null);
      const context = canvas.getContext('2d');
      if (context) {
        drawImages(context);
      }
    } else if (isResizing && selectedImageIndex !== null) {
      setIsResizing(false);
      setResizeCorner(null);
    }
  };

  useEffect(() => {
    const storedColor = localStorage.getItem('color');
    console.log(storedColor);
    if (storedColor) {
      setCanvasBackground(storedColor);
    }
    const storedUrl = localStorage.getItem('url1');
    if (storedUrl) {
      setBackgroundUrl(storedUrl);
    }
  }, []);
  const [isCharVisible, setIsCharVisible] = useState(false); // 控制 Char 组件的显示和隐藏
  const handleOnlineServiceClick = () => {
    setIsCharVisible(prevState => !prevState); // 使用函数式更新
  };

  const handleCharClose = () => {
    setIsCharVisible(false);
  };
  return (
    <div>
    
      {xyx !== null && xyy !== null && (
        <div className={style.xxx}>X轴坐标:<input type="text" value={xyx} style={{ width: 50 }} />&emsp;Y轴坐标:<input type="text" value={xyy} style={{ width: 50 }} />&emsp;&emsp;
          画布宽度:
          <input
            type="text"
            className="whith"
            value={canvasWidth}
            onChange={(e) => setCanvasWidth(Number(e.target.value))}
            style={{ width: 50 }}
          />
          &emsp;画布高度:
          <input
            type="text"
            className="hight"
            value={canvasHeight}
            onChange={(e) => setCanvasHeight(Number(e.target.value))}
            style={{ width: 50 }}
          /></div>
      )}
      <div className={style.top1}><Stylebeautification onDelete={deleteSelectedImage} img={img} /></div>
      <div
        className={style.Canvas}
        style={{
          background: backgroundUrl ? `url(${backgroundUrl}) no-repeat center center / 100% 100%` : canvasBackground,
          width: '100%',
          height: '100%',
        }}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onClick={handleCanvasClick}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}   
      >

        <canvas ref={canvasRef} style={{
          width: '1000px', // 这里设置的是画布元素的显示大小，可以设置为 '100%' 使其填满容器
          height: '100%',
        }} />
      </div>
      <div className={style.right111}>
        <button onClick={handleToggleWatermark}>
          {showWatermark ? '隐藏水印' : '显示水印'}
        </button>
        &emsp;&emsp;
        <button
          onClick={handleOnlineServiceClick}
        >
          在线客服
        </button>
        {isCharVisible && <Char onClose={handleCharClose} />}
        <button onClick={handleShare}>预览</button>
        {sharePreview && (
          <div className={style.modal}>
            <div className={style.modal}>
              <img src={canvasRef.current ? canvasRef.current.toDataURL('image/png') : ''} alt="Canvas Preview" />
              <button onClick={handleClosePreview} style={{ margin: '10px 0' }}>关闭预览</button>
            </div>
          </div>
        )}
      </div>
      
    </div>
  );
}

export default Canvas;
